<template>
  <view class="calendar-container" :class="{ 'dark-mode': isDarkMode }">
    <view class="calendar-header">
      <text class="header-title">每日一题</text>
    </view>

    <view class="date-info">
      <view class="current-date">
        <text class="date-value">{{ formattedDate }}</text>
        <text class="date-day">{{ dayOfWeek }}</text>
      </view>
    </view>

    <view class="calendar-grid">
      <view class="week-days">
        <text v-for="day in weekDays" :key="day">{{ day }}</text>
      </view>
      
      <view class="days-grid">
        <view 
          v-for="(day, index) in daysInMonth" 
          :key="index"
          :class="[
            'day-cell', 
            { 'other-month': day.otherMonth },
            { 'current-day': day.date === currentDay && day.month === currentMonth },
            { 'future-day': isFutureDay(day) }
          ]"
          @click="goToDailyProblem(day)"
          @mouseover="showProblemTooltip(day, $event)"
          @mouseleave="hideTooltip()"
        >
          {{ day.date }}
          <text v-if="!isFutureDay(day) && getDailyStatus(day) === 'completed'" class="day-completed">✓</text>
          <text v-else-if="!isFutureDay(day) && getDailyStatus(day) === 'assigned'" class="day-assigned">•</text>
        </view>
      </view>
      
      <view v-if="showTooltip" class="day-tooltip" :style="tooltipStyle">
        <view class="tooltip-title">{{ tooltipProblem.title }}</view>
        <view class="tooltip-difficulty" :style="{ color: getDifficultyColor(tooltipProblem.difficulty) }">
          {{ tooltipProblem.difficulty }}
        </view>
        <view class="tooltip-hint">点击跳转到题目</view>
      </view>
    </view>
    
    <view class="contest-countdown">
      <view class="countdown-title">距离比赛</view>
      
      <view class="contest-item" v-for="(contest, index) in upcomingContests" :key="index">
        <view class="contest-name">{{ contest.name }}</view>
        <view class="contest-info">
          <text class="contest-date">{{ contest.date }}</text>
          <text class="contest-days">剩余 {{ contest.daysLeft }} 天</text>
        </view>
        <view v-if="contest.predictedScore" class="predicted-score">
          预测分数: <text>{{ contest.predictedScore }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getThemeMode } from '@/utils/themeManager.js';

export default {
  data() {
    return {
      currentDate: new Date(),
      weekDays: ['日', '一', '二', '三', '四', '五', '六'],
      currentMonth: new Date().getMonth(),
      currentDay: new Date().getDate(),
      hasPassed: true, // 是否通过入门测试
      upcomingContests: [
        {
          name: 'NOI 2023',
          date: '2023-07-15',
          daysLeft: this.calculateDaysLeft('2023-07-15'),
          predictedScore: this.hasPassed ? '85' : null
        },
        {
          name: 'NOIP 2023',
          date: '2023-11-25',
          daysLeft: this.calculateDaysLeft('2023-11-25'),
          predictedScore: this.hasPassed ? '92' : null
        },
        {
          name: '蓝桥杯 2023',
          date: '2023-09-10',
          daysLeft: this.calculateDaysLeft('2023-09-10'),
          predictedScore: this.hasPassed ? '78' : null
        }
      ],
      dailyProblems: {},
      showTooltip: false,
      tooltipProblem: {},
      tooltipStyle: {
        top: '0px',
        left: '0px'
      },
      isDarkMode: false
    };
  },
  computed: {
    formattedDate() {
      const year = this.currentDate.getFullYear();
      const month = this.currentDate.getMonth() + 1;
      const day = this.currentDate.getDate();
      return `${year}年${month}月${day}日`;
    },
    dayOfWeek() {
      const days = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
      return days[this.currentDate.getDay()];
    },
    daysInMonth() {
      const year = this.currentDate.getFullYear();
      const month = this.currentDate.getMonth();
      
      // 当前月的第一天
      const firstDay = new Date(year, month, 1);
      // 当前月的最后一天
      const lastDay = new Date(year, month + 1, 0);
      
      const daysArray = [];
      
      // 填充当前月之前的日期
      const firstDayOfWeek = firstDay.getDay();
      const prevMonthLastDay = new Date(year, month, 0).getDate();
      
      for (let i = firstDayOfWeek - 1; i >= 0; i--) {
        daysArray.push({
          date: prevMonthLastDay - i,
          month: month - 1,
          otherMonth: true
        });
      }
      
      // 填充当前月的日期
      for (let i = 1; i <= lastDay.getDate(); i++) {
        daysArray.push({
          date: i,
          month: month,
          otherMonth: false
        });
      }
      
      // 填充当前月之后的日期
      const remainingCells = 42 - daysArray.length; // 6周 x 7天 = 42个单元格
      for (let i = 1; i <= remainingCells; i++) {
        daysArray.push({
          date: i,
          month: month + 1,
          otherMonth: true
        });
      }
      
      return daysArray;
    }
  },
  created() {
    this.initDailyProblems();
  },
  mounted() {
    // 检查当前主题
    this.isDarkMode = getThemeMode();
    
    // 监听全局主题变更
    uni.$on('global-theme-changed', (isDark) => {
      this.isDarkMode = isDark;
    });
  },
  beforeDestroy() {
    uni.$off('global-theme-changed');
  },
  methods: {
    calculateDaysLeft(dateString) {
      const targetDate = new Date(dateString);
      const now = new Date();
      const diffTime = targetDate - now;
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      return diffDays > 0 ? diffDays : 0;
    },
    initDailyProblems() {
      const today = new Date();
      const year = today.getFullYear();
      const month = today.getMonth();
      
      // 模拟数据：为本月的每一天随机分配题目
      const daysInMonth = new Date(year, month + 1, 0).getDate();
      
      for (let i = 1; i <= daysInMonth; i++) {
        const problemId = 1000 + Math.floor(Math.random() * 100);
        const dateKey = `${year}-${month+1}-${i}`;
        this.dailyProblems[dateKey] = {
          id: problemId,
          title: `每日一题 ${i}：算法挑战`,
          difficulty: ['入门', '简单', '中等', '困难', '专家'][Math.floor(Math.random() * 5)],
          completed: i < today.getDate() ? Math.random() > 0.5 : false // 今天之前的随机完成状态
        };
      }
    },
    getDailyStatus(day) {
      if (day.otherMonth) return 'none';
      
      const dateKey = `${this.currentDate.getFullYear()}-${day.month+1}-${day.date}`;
      const problem = this.dailyProblems[dateKey];
      
      if (!problem) return 'none';
      return problem.completed ? 'completed' : 'assigned';
    },
    goToDailyProblem(day) {
      if (day.otherMonth || this.isFutureDay(day)) return;
      
      const dateKey = `${this.currentDate.getFullYear()}-${day.month+1}-${day.date}`;
      const problem = this.dailyProblems[dateKey];
      
      if (problem) {
        uni.navigateTo({
          url: `/pages/problem/detail?id=${problem.id}`
        });
      }
    },
    showProblemTooltip(day, event) {
      if (day.otherMonth || this.isFutureDay(day)) return;
      
      const dateKey = `${this.currentDate.getFullYear()}-${day.month+1}-${day.date}`;
      const problem = this.dailyProblems[dateKey];
      
      if (problem) {
        this.tooltipProblem = problem;
        this.showTooltip = true;
        
        this.tooltipStyle = {
          position: 'fixed',
          top: `${event.clientY + 10}px`,
          left: `${event.clientX - 100}px`,
          zIndex: 1000
        };
      }
    },
    hideTooltip() {
      this.showTooltip = false;
    },
    getDifficultyColor(difficulty) {
      const diffColors = {
        '入门': '#00b800',
        '简单': '#3498db', 
        '中等': '#f39c12', 
        '困难': '#e74c3c', 
        '专家': '#9b59b6'
      };
      return diffColors[difficulty] || '#666';
    },
    isFutureDay(day) {
      const today = new Date();
      const currentMonth = today.getMonth();
      const currentDate = today.getDate();
      
      return (day.month === currentMonth && day.date > currentDate) || day.month > currentMonth;
    }
  }
};
</script>

<style>
.calendar-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #ffffff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.dark-mode.calendar-container {
  background-color: #1e1e1e;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  color: #e0e0e0;
}

.calendar-header {
  margin-bottom: 15px;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.dark-mode .header-title {
  color: #ffffff;
}

.date-info {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
}

.dark-mode .date-info {
  background-color: #2a2a2a;
}

.current-date {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.date-value {
  font-size: 16px;
  font-weight: bold;
}

.dark-mode .date-value {
  color: #e0e0e0;
}

.date-day {
  color: #666;
}

.dark-mode .date-day {
  color: #aaa;
}

.calendar-grid {
  position: relative;
  margin-bottom: 20px;
}

.week-days {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  text-align: center;
  margin-bottom: 10px;
}

.week-days text {
  font-size: 14px;
  color: #666;
}

.dark-mode .week-days text {
  color: #888;
}

.days-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  grid-gap: 5px;
}

.day-cell {
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  border-radius: 4px;
  position: relative;
  cursor: pointer;
  background-color: #f9f9f9;
}

.dark-mode .day-cell {
  background-color: #2a2a2a;
}

.day-cell.other-month {
  color: #ccc;
}

.dark-mode .day-cell.other-month {
  color: #555;
}

.day-cell.current-day {
  background-color: #20C0B8;
  color: white;
}

.dark-mode .day-cell.current-day {
  background-color: #20C0B8;
}

.day-cell.future-day {
  color: #ccc;
  cursor: default;
}

.dark-mode .day-cell.future-day {
  color: #555;
}

.day-completed {
  position: absolute;
  top: 2px;
  right: 2px;
  font-size: 10px;
  color: #00b800;
}

.day-assigned {
  position: absolute;
  bottom: 2px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 14px;
  color: #20C0B8;
}

.day-tooltip {
  position: fixed;
  background: white;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  padding: 10px;
  width: 200px;
  z-index: 1000;
}

.dark-mode .day-tooltip {
  background-color: #2a2a2a;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
}

.tooltip-title {
  font-weight: bold;
  margin-bottom: 5px;
}

.dark-mode .tooltip-title {
  color: #ffffff;
}

.tooltip-difficulty {
  font-size: 12px;
  margin-bottom: 5px;
}

.dark-mode .tooltip-difficulty {
  color: #ffffff;
}

.tooltip-hint {
  font-size: 12px;
  color: #666;
  font-style: italic;
}

.dark-mode .tooltip-hint {
  color: #aaa;
}

.contest-countdown {
  flex: 1;
}

.countdown-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
}

.dark-mode .countdown-title {
  color: #ffffff;
}

.contest-item {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 10px;
}

.dark-mode .contest-item {
  background-color: #2a2a2a;
}

.contest-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.dark-mode .contest-name {
  color: #ffffff;
}

.contest-info {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.dark-mode .contest-info {
  color: #aaa;
}

.contest-days {
  color: #ff5722;
  font-weight: bold;
}

.dark-mode .contest-days {
  color: #ff7675;
}

.predicted-score {
  font-size: 14px;
}

.dark-mode .predicted-score {
  color: #ffffff;
}

.predicted-score text {
  color: #20C0B8;
  font-weight: bold;
}
</style> 